package www.golf.web.gonwubu.edit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JExcelApiExporter;

import org.python.antlr.PythonParser.return_stmt_return;
import org.zkoss.util.media.AMedia;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Iframe;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.SimpleTreeModel;
import org.zkoss.zul.SimpleTreeNode;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treecell;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.TreeitemRenderer;
import org.zkoss.zul.Treerow;
import org.zkoss.zul.Window;

import www.golf.ibatis.bean.A_project;
import www.golf.ibatis.bean.A_projectShow;
import www.golf.ibatis.bean.Connection;
import www.golf.ibatis.bean.ConnectionShow;
import www.golf.ibatis.bean.Projectset;
import www.golf.web.gonwubu.ConnectionControl;
import www.golf.web.session.WebSession;
import www.golf.web.util.UtilListbox;
import www.golf.web.util.UtilZKObject;

public class ConnectionEdit extends WebSession{
	UtilZKObject ZKObj =new UtilZKObject(this);
	UtilListbox lb= new UtilListbox();
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	Map argmap= Executions.getCurrent().getArg();
	String agreements="0";
	int status=0;
	public void initialize() {
		setListData(this);
		setTreeData(null);
		if(argmap.get("pid")!=null){
			status=super.edit;
			String value=(String) argmap.get("pid");
			setEditdata(value);
			checkJob();
		}else{
			status=super.add;
			workflow(1,true);
		}
	}
	public void checkJob(){
		int value=Integer.parseInt((String)argmap.get("data_type"));
		if(getUserPower()<5&&value==1){
			getFellow("ed_audit").setVisible(true);
		}
	}
	
	public void setEditdata(String value){
		ConnectionShow bean=null;
		List con_list=null;
		List supervision_list=null;
		List agrees_list=null;
		try {
			 bean = (ConnectionShow)dbSession().queryForObject("Connection.getConnection",Integer.parseInt(value));
			 con_list=(List)dbSession().queryForList("Connection.getConnection_type_list",bean.getConnection_type_id());
			 supervision_list=(List)dbSession().queryForList("Connection.getCon_Supervision_list",Integer.parseInt(value));
			 agrees_list=(List)dbSession().queryForList("Connection.getCon_Agrees_list",Integer.parseInt(value));
			 dbSessionClose();
		} catch (Exception e) {
			e.printStackTrace();
		}
		int type_child = 0;
		for(Object obj:con_list){
			if((Integer)((Map)obj).get("parent_id")==-1){
				ZKObj.setObjectValue("f_type", String.valueOf(((Map)obj).get("pid")));
				setListTypeData();
			}else{
				type_child=(Integer)((Map)obj).get("pid");
			}
		}
		ZKObj.setObjectValue("ed_pid", value);
		ZKObj.setObjectValue("ed_serial", bean.getSerial_number());
		ZKObj.setObjectValue("f_child_type", String.valueOf(type_child));
		ZKObj.setObjectValue("ed_title", bean.getTitle());
		ZKObj.setObjectValue("ed_note", bean.getNote());;
		ZKObj.setObjectValue("ed_money1", bean.getMoney());
		ZKObj.setObjectValue("ed_money2", bean.getMoney2());
		ZKObj.setObjectValue("ed_data_type", bean.getProject_data_type_id());
		if(!bean.isIsmoney()){
			Intbox tb_in=(Intbox) getFellow("ed_money1");
			Intbox tb_out=(Intbox) getFellow("ed_money2");
			tb_in.setDisabled(true);
			tb_out.setDisabled(true);
		}
		ZKObj.setObjectValue("ed_ismoney", bean.isIsmoney());
		ZKObj.setObjectValue("ed_content", bean.getContent());
		setSupervision(bean.getAgreements());
		if(supervision_list.size()!=0){
			for(Object obj:supervision_list){
				for(Object listitem:((Listbox)getFellow("ed_a_supervision_id")).getItems()){
					Listitem item=(Listitem)listitem;
					if(item.getValue().equals(String.valueOf(((Map)obj).get("a_supervision_id")))){
						item.setSelected(true);
					}
				}
				
			}
			Checkbox cb=(Checkbox) getFellow("ed_supervision");
			cb.setChecked(true);
			openSupervision();
		}
		String agrees="";
		for(Object obj:agrees_list){
			agrees=agrees+((Map)obj).get("a_project_id")+",";
		}
		agrees=agrees.substring(0, agrees.length()-1);
		setTreeData(agrees);
	}
	public void setTreeData(final String load_data){
		agreements=(load_data!=null)?load_data:agreements;
		Tree tree=((Tree)getFellow("agree_tree"));
		SimpleTreeNode node=null;
		try {
			node = setTreeNode("n", dbSession().queryForList("Agreement.select_Agree_Tree"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		SimpleTreeModel treeModel = new SimpleTreeModel(node);
		tree.setModel(treeModel);
		tree.setTreeitemRenderer(new TreeitemRenderer(){
			@Override
			public void render(Treeitem item, Object data) throws Exception {
				SimpleTreeNode t = (SimpleTreeNode)data;
				Map m=(Map)t.getData();
				Treecell tc = new Treecell();
				Treerow tr = new Treerow();
				if(item.getTreerow()==null){
					tr = new Treerow();
					tr.setParent(item);
				}else{
					tr = item.getTreerow(); 
					tr.getChildren().clear();
				}
				String pid=((String)m.get("pid"));
				Character d=pid.charAt(0);
				if(d.equals('a')){
					Checkbox cb=new Checkbox();
					cb.setAttribute("pid", pid.substring(1, pid.length()));
					cb.addEventListener("onCheck", new EventListener(){
						public void onEvent(Event event) throws Exception {
							if(((Checkbox)event.getTarget()).isChecked()){
								String array[]=agreements.split(",");
								String pid=(String) event.getTarget().getAttribute("pid");
								boolean ck=true;
								for(int i=0;i<array.length;i++){
									if(pid.equals(array[i])){
										ck=false;
										break;
									}
								}
								if(ck){
									agreements=agreements+","+pid;
								}
							}else{
								String array[]=agreements.split(",");
								String pid=(String) event.getTarget().getAttribute("pid");
								String agree="";
								boolean ck=true;
								for(int i=0;i<array.length;i++){
									if(!pid.equals(array[i])&&i==0){
										agree=array[i];
									}else if(!pid.equals(array[i])){
										agree=agree+","+array[i];
									}
								}
								agreements=agree;
							}
						}
					});
					Label lb =new Label((String) m.get("name"));
					tc.appendChild(cb);
					tc.appendChild(lb);
					tc.setParent(tr);
					if(load_data!=null){
						String agree[]=load_data.split(",");
						for(int i=0;i<agree.length;i++){
							try{
								if(agree[i].equals((String)cb.getAttribute("pid"))){
									cb.setChecked(true);
								}
							}catch(Exception e){
								e.printStackTrace();
							}
						}
					}
				}else{
					tc.setLabel((String) m.get("name"));
					tc.setParent(tr);
					if(load_data!=null){
						item.setOpen(true);
					}
				}
			}
		});
	}
	
	public void view(){
		Connection bean=setBean(1, null);
		bean.setSerial_number(null);
		constructPDF(bean);
	}
	public void constructPDF(Connection bean){
		String send=null;
		try {
			send=(String) dbSession().queryForObject("Connection.selectSend",bean);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		HashMap<String, String> map = new HashMap<String, String>(); 
		map.put("title_message", (Integer.parseInt(ZKObj.getValue("f_type"))==9)?"建设工程联系单":"建设工程通知单");
		map.put("tp", (Integer.parseInt(ZKObj.getValue("f_type"))==9)?"C2":"C1");
		getDesktop().getExecution().sendRedirect("/index.zul");
		HashMap<String, String> dmap = new HashMap<String, String>(); 
		dmap.put("title", bean.getTitle());
		dmap.put("serial", bean.getSerial_number()==null?"預覽模式":bean.getSerial_number());
		dmap.put("note", bean.getNote());
		dmap.put("give", send);
		dmap.put("content", bean.getContent());
		createPDF("connection_report",map,dmap,"PDF_name");
	}
	public void view_refresh(){
		Iterator it=Executions.getCurrent().getDesktop().getPage("main_content").getFellows().iterator();
		ConnectionControl win=(ConnectionControl)getm_content().getFellow("p_w");
		win.initialize();
	}
	
	public void submit(){
		try {
			if(status==add){
			    Connection bean=setBean(1, null);
			    dbSession().insert("Connection.insertConnection", bean);
			    bean.setSerial_number((String) dbSession().queryForObject("Connection.lastConnection_key"));
				try {
					view_refresh();
					constructPDF(bean);
					this.detach();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(status==edit){
				if(updateData(1)){
					Messagebox.show("存檔完毕");
					view_refresh();
					constructPDF(setBean(1, null));
					this.detach();
				}else{
					Messagebox.show("未填写完整");
				}
				view_refresh();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void audit(){
		try {
			if(updateData(2)){
				Messagebox.show("存檔与稽核完毕");
				view_refresh();
				this.detach();
			}else{
				Messagebox.show("未填写完整");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	public boolean updateData(int i) throws SQLException{
		Connection bean=setBean(1, null);
		bean.setProject_data_type_id(i);
		if("".equals(bean.getAgreements())||
		"".equals(bean.getNote())||"".equals(bean.getTitle())||
		"".equals(bean.getContent())||bean.getConnection_type_id()==0){
			return false;
		}else{
			dbSession().update("Connection.updateConnection", bean);
			return true;
		}
	}
	public Connection setBean(int data_type,String books){
		Connection bean= new Connection();
		SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd");
		bean.setTitle(ZKObj.getValue("ed_title"));
		bean.setAccount_id(getUserPid());
		bean.setNote(ZKObj.getValue("ed_note"));
		bean.setMoney(("".equals(ZKObj.getValue("ed_money1"))?0:Integer.parseInt(ZKObj.getValue("ed_money1"))));
		bean.setMoney2(("".equals(ZKObj.getValue("ed_money2"))?0:Integer.parseInt(ZKObj.getValue("ed_money2"))));
		bean.setBooks(books);
		bean.setIsmoney("1".equals(ZKObj.getValue("ed_ismoney"))?true:false);
		bean.setConnection_type_id(Integer.parseInt("".equals(ZKObj.getValue("f_child_type"))?"0":ZKObj.getValue("f_child_type")));
		bean.setProject_data_type_id(data_type);
		bean.setContent(((Textbox)ZKObj.getContrain().getFellow("ed_content")).getText());
		bean.setAgreements(agreements);
		bean.setSupervisions(getSupervisions());
		if(status==super.edit){
			bean.setPid(Integer.parseInt(ZKObj.getValue("ed_pid")));
			bean.setSerial_number(ZKObj.getValue("ed_serial"));
		}else{
			bean.setSerial_number((Integer.parseInt(ZKObj.getValue("f_type"))==9)?"C2":"C1"
					+"-"+df.format(new java.util.Date())+"-");
		}
		return bean;
	}
	public void setList_f_child_typeData(){
		int value=Integer.parseInt(ZKObj.getObjectValue(getFellow("f_child_type")));
		try {
			Map m=(Map)dbSession().queryForObject("Connection.getConnection_type", value);
			ZKObj.setObjectValue("type_define", m.get("note"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public void setListNoteData(){
		if(ZKObj.getObjectValue(getFellow("f_child_type")).equals("")){
			ZKObj.setObjectValue("type_define", "");
		}else{
			setList_f_child_typeData();
			Intbox tb_in=(Intbox) getFellow("ed_money1");
			Intbox tb_out=(Intbox) getFellow("ed_money2");
			Checkbox ck=(Checkbox)getFellow("ed_ismoney");
			ck.setChecked(false);
			ck.setDisabled(false);
			tb_in.setDisabled(true);
			tb_in.setValue(0);
			tb_out.setDisabled(true);
			tb_out.setValue(0);
		}
			
	}
	public void setListTypeData(){
		if(ZKObj.getObjectValue(getFellow("f_type")).equals("")){
			ZKObj.clearValue("f_child_type");
		}else{
			int value=Integer.parseInt(ZKObj.getObjectValue(getFellow("f_type")));
			((Listbox)getFellow("f_child_type")).setDisabled(false);
			setList(this,"Connection.selectConnection_type_list","f_child_type",value);
		}
		Intbox tb_in=(Intbox) getFellow("ed_money1");
		Intbox tb_out=(Intbox) getFellow("ed_money2");
		Checkbox ck=(Checkbox)getFellow("ed_ismoney");
		if(ZKObj.getObjectValue(getFellow("f_child_type")).equals("6")){
			ck.setChecked(false);
			ck.setDisabled(false);
			tb_in.setValue(0);
			tb_out.setValue(0);
		}else if(ZKObj.getObjectValue(getFellow("f_child_type")).equals("2")
				||ZKObj.getObjectValue(getFellow("f_child_type")).equals("3")
				||ZKObj.getObjectValue(getFellow("f_child_type")).equals("4")){
			ck.setChecked(true);
			ck.setDisabled(true);
			ismoney_check();
		}
	}
	public void setListData(Window win){
		((Listbox)win.getFellow("f_child_type")).setDisabled(true);
		setList(win,"Connection.selectConnection_type_list","f_type");
	}
	public String setDate(Date date){
		return date!=null?sdf.format(date):null;
	}
	public void workflow(int i,boolean next){
		try {
			for(int j=1;j<=4;j++){
				getFellow("set"+j).setVisible(true);
			}
			if(checkerflow(i,next)){
				for(int j=1;j<=4;j++){
					if(i==j){
						getFellow("flow"+j).setVisible(true);
					}else{
						getFellow("flow"+j).setVisible(false);
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public boolean checkerflow(int i,boolean next) throws InterruptedException {
		boolean checek=true;
		switch (i) {
		case 1:
			//回初始
			break;
		case 2:
			if(ZKObj.getObjectValue(getFellow("f_child_type")).equals("")){
				Messagebox.show("请选择属性", "未填写完整", Messagebox.OK, Messagebox.QUESTION);
				checek=false;
			}
			break;
		case 3:
			if(agreements.equals("0")){
				Messagebox.show("请选择对应合同", "未填写完整", Messagebox.OK, Messagebox.QUESTION);
				checek=false;
			}else{
				if(ZKObj.getObjectValue(getFellow("f_child_type")).equals("6")){
					checek=false;
					if(next)workflow(4,next);else workflow(2,next);;
				}else if(ZKObj.getObjectValue(getFellow("f_child_type")).equals("2")
						||ZKObj.getObjectValue(getFellow("f_child_type")).equals("3")
						||ZKObj.getObjectValue(getFellow("f_child_type")).equals("4")){
					ismoney_check();
				}
				if(next){setSupervision(agreements);};
			}
			
			break;
		case 4:
			break;
		default:
			break;
		}
		return checek;
	}
	public void ismoney_check(){
		Checkbox ck=(Checkbox)getFellow("ed_ismoney");
		Intbox tb_in=(Intbox) getFellow("ed_money1");
		Intbox tb_out=(Intbox) getFellow("ed_money2");
		if(ck.isChecked()){
			tb_in.setDisabled(false);
			tb_out.setDisabled(false);
		}else{
			tb_in.setConstraint("");
			tb_out.setConstraint("");
			tb_in.setValue(null);
			tb_out.setValue(null);
			tb_in.setDisabled(true);
			tb_out.setDisabled(true);
		}
	}
	public String getSupervisions(){
		String supervisions="";
		Iterator it=((Listbox)getFellow("ed_a_supervision_id")).getSelectedItems().iterator();
		while(it.hasNext()){
			Listitem item=(Listitem)it.next();
			supervisions=supervisions+","+item.getValue();
		}
		return "".equals(supervisions)?"0":supervisions.substring(1);
	}
	public void setSupervision(String agrees){
		setList(this,"Connection.select_a_supervision_list","ed_a_supervision_id",agrees);
		try{
			((Listbox)getFellow("ed_a_supervision_id")).removeItemAt(0);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void openSupervision(){
		Checkbox cb=(Checkbox) getFellow("ed_supervision");
		Listbox lb=(Listbox)getFellow("ed_a_supervision_id");
		if(cb.isChecked()){
			lb.setVisible(true);
		}else{
			lb.setVisible(false);
			lb.clearSelection();
		}
	}
}
